<?php 

/*

***************************************
*                                     *
* Copyright 2011 David Matthew Pugh   *
* Contact Info:thebravedave@gmail.com *
*                                     *
***************************************

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

include('check_encryption_session.php');
require_once ('usps.php');  
require_once ('ups.php');
require_once("Mail.php");
require_once "./services/webservices.php"; 
require_once ('WidgetShoppingCart.php');
//start session annd if not have session variable named total then redirect to cart.php

 
if(!isset($_SESSION['total']))
{                                                         
      header("location:cart.php");
}
  
 
 
$page_title = 'Step 1: Package Destination/Shipping Service'; 
  
include("./includes/header.php");                            


// Check for form submission.
if (isset($_POST['zip_code'])) 
{  

     //if the order information has been submitted then assign the POST data into variable, then assign them to session variables.    
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $street_address = $_POST['street_address'];
    $city = $_POST['city'];
    $state = $_POST['state'];
    $zip_code = $_POST['zip_code'];   
    $_SESSION['shipping_first_name'] = $first_name;
    $_SESSION['shipping_last_name'] = $last_name;
    $_SESSION['shipping_street_address'] = $street_address;
    $_SESSION['shipping_city'] = $city;
    $_SESSION['shipping_state'] = $state;
    $_SESSION['shipping_zip_code'] = $zip_code;   
}

// shipping variable information needs to be documented in case there is no data, in which case errors will be given when this session data is parsed into the html forms fields to let the user "know what they typed"
if(isset($_SESSION['shipping_first_name']))
{
    $first_name = $_SESSION['shipping_first_name'];
    $last_name = $_SESSION['shipping_last_name'];
    $street_address = $_SESSION['shipping_street_address'];
    $city = $_SESSION['shipping_city'];
    $state = $_SESSION['shipping_state'];
    $zip_code = $_SESSION['shipping_zip_code'];
    
   
}
else
{
    $first_name ="";
    $last_name = "";
    $street_address = "";
    $city = "";
    $state = "";
    $zip_code = "";
}
    

// Show the form.



//javascript to make sure the user filled out form completely    
?>
<script type="text/javascript">
function clientinputcheck()
{
    go=true;
    if(document.getElementById("first_name").value=="" || document.getElementById("last_name").value=="" || document.getElementById("street_address").value=="" || document.getElementById("city").value=="" || document.getElementById("zip_code").value=="")
    {
        alert("Please completely fill out the packages destination");
        go=false;
        return false;
    }
    if(go)
    {
        
        return true;
    }
}
</script>
<form action="orderinformation.php" method="post">

<table border="0" width="90%" cellspacing="2" cellpadding="2" align="center">
    
    <tr>
        <td align="right">First Name:</td>
        <td align="left"><input type="text" name="first_name" id="first_name" value="<?php echo $first_name; ?>"></td>
    </tr>     
    
    <tr>
        <td align="right">Last Name:</td>
        <td align="left"><input type="text" name="last_name" id="last_name" value="<?php echo $last_name; ?>"></td>
    </tr>
    
    <tr>
        <td align="right">Street Address:</td>
        <td align="left"><input type="text" name="street_address" id="street_address" value="<?php echo $street_address; ?>"></td>
    </tr>
    
    <tr>
        <td align="right">City:</td>
        <td align="left"><input type="text" name="city" id="city" value="<?php echo $city; ?>"></td>
    </tr>
   
    <tr>
        <td align="right">State:</td>
        <td align="left"><select name="state">
        <?php
        if(isset($_SESSION['shipping_state']))
        {
            echo ' <option value="' . $state . '">' . $state . '</option>"' ; 
        }
        else
        {
            echo '<option value="AL">Alabama</option>';  
        }
        ?>
                            
                            <option value="AK">Alaska</option>
                            <option value="AZ">Arizona</option>
                            <option value="AR">Arkansas</option>
                            <option value="CA">California</option>
                            <option value="CO">Colorado</option>
                            <option value="CT">Connecticut</option>
                            <option value="DE">Delaware</option>
                            <option value="DC">Dist of Columbia</option>
                            <option value="FL">Florida</option>
                            <option value="GA">Georgia</option>
                            <option value="HI">Hawaii</option>
                            <option value="ID">Idaho</option>
                            <option value="IL">Illinois</option>
                            <option value="IN">Indiana</option>
                            <option value="IA">Iowa</option>
                            <option value="KS">Kansas</option>
                            <option value="KY">Kentucky</option>
                            <option value="LA">Louisiana</option>
                            <option value="ME">Maine</option>
                            <option value="MD">Maryland</option>
                            <option value="MA">Massachusetts</option>
                            <option value="MI">Michigan</option>
                            <option value="MN">Minnesota</option>
                            <option value="MS">Mississippi</option>
                            <option value="MO">Missouri</option>
                            <option value="MT">Montana</option>
                            <option value="NE">Nebraska</option>
                            <option value="NV">Nevada</option>
                            <option value="NH">New Hampshire</option>
                            <option value="NJ">New Jersey</option>
                            <option value="NM">New Mexico</option>
                            <option value="NY">New York</option>
                            <option value="NC">North Carolina</option>
                            <option value="ND">North Dakota</option>
                            <option value="OH">Ohio</option>
                            <option value="OK">Oklahoma</option>
                            <option value="OR">Oregon</option>
                            <option value="PA">Pennsylvania</option>
                            <option value="RI">Rhode Island</option>
                            <option value="SC">South Carolina</option>
                            <option value="SD">South Dakota</option>
                            <option value="TN">Tennessee</option>
                            <option value="TX">Texas</option>
                            <option value="UT">Utah</option>
                            <option value="VT">Vermont</option>
                            <option value="VA">Virginia</option>
                            <option value="WA">Washington</option>
                            <option value="WV">West Virginia</option>
                            <option value="WI">Wisconsin</option>
                            <option value="WY">Wyoming</option>

                            </select>
                       </td>   
    </tr>
    
    <tr>
        <td align="right">Zip Code:</td>
        <td align="left"><input type="text" name="zip_code" id="zip_code" value="<?php echo $zip_code; ?>"></td>
    </tr>
    
   
    
    
    
    <tr>
        <td align="center" colspan="2"><input name="submit" value="get shipping options for this address" onclick="javascript: return clientinputcheck();" type="submit" class="button" /></td>
        
    </tr>
    <br />
    
</table>
</form>
<br />
<hr>    
<?php
//if the shipping zip code session variable is set then allow the dropbox with shipping services from ups. 
if(isset($_SESSION['shipping_zip_code']))
{   
    
    require_once "address_validation_functions.php"; 
    
   
    $params = addressvalidation($city, $state, $zip_code);
    $addressvalidationresults = GetAddressValidationResults($params);  
    $newarray = array();
    $temp_int = 0;
    foreach($addressvalidationresults as $array)
    {    
        $newarray = $array;
        $quality = $newarray["ADDRESSVALIDATIONRESULT"]["QUALITY"];
        
        if($quality == 1)
        {
            $address_confirmed = "true";
        }
        else
        {  
            if($temp_int==0)
            {
                print "<b>The zip code you entered doesnt match with the city/state you entered.<br /> Please re-enter or choose from the following list.<br /></b><br /><br />";
            }
            $address_confirmed = "false";  
            $response_rank = $newarray["ADDRESSVALIDATIONRESULT"]["RANK"];
            $response_city = $newarray["ADDRESSVALIDATIONRESULT"]["ADDRESS"]["CITY"];
            $response_state = $newarray["ADDRESSVALIDATIONRESULT"]["ADDRESS"]["STATEPROVINCECODE"];
            $response_zip_code_lowend = (int)$newarray["ADDRESSVALIDATIONRESULT"]["POSTALCODELOWEND"];
            $response_zip_code_highend = (int)$newarray["ADDRESSVALIDATIONRESULT"]["POSTALCODEHIGHEND"];
           
           
            
            $zip_code_averaged = ($response_zip_code_highend + $response_zip_code_lowend)/2;
            $zip_code_averaged = round($zip_code_averaged);
            
?>
           <div class="doubleborderclear">
           <form action="orderinformation.php" method="post">
           <input type="hidden" name="first_name" value="<?php echo $first_name;?>">
           <input type="hidden" name="last_name" value="<?php echo $last_name;?>">
           <input type="hidden" name="street_address" value="<?php echo $street_address;?>"> 
           <input type="hidden" name="city" value="<?php echo $response_city;?>">    
           <input type="hidden" name="state" value="<?php echo $response_state;?>"> 
           <input type="hidden" name="zip_code" value="<?php echo $response_zip_code_lowend;?>">  
             
              
              
            
            
            <div class="doubleborderrightmargin">
                <b>Rank:#</b><?php echo $response_rank  ?> <br />

                <b>City:</b><?php echo $response_city ?><br /> 
 
                <b>State:</b><?php echo $response_state ?><br />
             
                <b>Postal Code Range:</b><?php echo  $response_zip_code_lowend . "-" . $response_zip_code_highend?><br /> 
            
            
           
            <input type="submit" id="submit" value="Submit New Address">
            </div>  
            <br /><br />
            </form>
    
<?php      
           }
                $temp_int++;
    }         
    
    
     
    if($address_confirmed=="true")
    {  
            
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
/////////////////////////////S H I P P I N G  E S T I M A T I O N  S E C T I O N ////////////////////////////////////////S H I P P I N G  E S T I M A T I O N  S E C T I O N //////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////          
          
    $cart = unserialize($_SESSION['cart']);      
    $cartidentifier = $cart->identifier;  
    $sortarray = array();
    $master_item_id_array = $sortarray;
    
   
    $sw_gw_id_array = array();
    $itemweightarray = array();
    $gw_sw_key_array = array();
    $itemprice = 0; 
    $num = 0;  
          
    foreach ($cart->items as $key => $info)
    {             
        $array = $info;
        $qty = $info['qty'];  
        $price = $array['price'];
        $itemprice = $itemprice + $price*$qty;
        $sw_id = $info['sw_id']; 
        $gw_id = $info['gw_id'];
        $weight = $array['weight'];
        
        $tmpnum = 0;
        while($tmpnum != $qty)
        {
            if($sw_id == "")
            {
               $itemweightarray[$num] = $weight;
               $sw_gw_id_array[$num] = $gw_id; 
               $num++;    
            }
            else
            {
                $itemweightarray[$num] = $weight;
                $sw_gw_id_array[$num] = $sw_id;
                $gw_sw_key_array[$sw_id] = $gw_id;
                $num++;
            }
            $tmpnum++; 
        }    
                                                                 
    } 
   // echo "<br />" ;print_r($itemweightarray); echo '<br />';        
  
    $aloneweightarray = array();   
    $aloneweightarraycounter = 0;
    $groupedweightarray = array();
    $groupedweightarraycounter = 0;
    foreach($itemweightarray as $id=>$itemWeight)
    {   
         $current_id = $sw_gw_id_array[$id];
        
        if(array_key_exists($current_id, $gw_sw_key_array))
        {
            $current_gw_id = $gw_sw_key_array[$sw_gw_id_array[$id]];
        }
        else
        {
            $current_gw_id = $current_id;
        }
        $item = new item();
        $item->gw_id = $current_gw_id;
      
        $itemResponse = $item->getitembyid();
        $itemXml = new SimpleXMLElement($itemResponse);
                       
        $packing = (string)$itemXml->Item->packing;
       
        if($packing == "alone")
        {
            $tmparray = array();  
            $tmparray[$current_id] = $itemWeight;
            $aloneweightarray[$aloneweightarraycounter] = $tmparray;      
            $aloneweightarraycounter++;                
        }
        else
        {
            $tmparray = array();        
            $tmparray[$current_id] = $itemWeight;      
            $groupedweightarray[$groupedweightarraycounter] = $tmparray;
            $groupedweightarraycounter++;
        }
    }
   
 
    $getrequest = new shipping();
    $getresponse = $getrequest->getshippingservices();
    $xml = new SimpleXMLElement($getresponse);
    $Item_Count = $xml->Item_Count;

    if($Item_Count > 0)
    {     
        
        unset($_SESSION['services_total']);
        $services_total = array();        
        foreach($xml->Item as $eachitem)
        {
            $service_invalid = "false"; 
            $service_id = (string)$eachitem->id;
            $carrier_id = $eachitem->carrier_id;
            $carrier_service_id = (string) $eachitem->service_id;
            $service = $eachitem->service;
            $service_weight_max = $eachitem->weight_max;          
            $service_weight_max  = (int)$service_weight_max;
            $carrier_id = (string)$carrier_id;
            $service = (string)$service;
                            
         
            //must find out if any of the items weights are heavier than the maximum weight for the service. if so we cannot use this service
            foreach($itemweightarray as $key => $value)
            {
                if($value > $service_weight_max)
                {
                   
                    $service_invalid = "true";
                }
            }
           
            if($service_invalid == "false")
            {
                
            
            
              //must find out if the service is by UPS or USPS. 
              $getrequest = new shipping();
              $getrequest->carrier_id = $carrier_id;
              $getresponse = $getrequest->getshippingcarrierbycarrierid();
              $xml = new SimpleXMLElement($getresponse);
               
              foreach($xml->Item as $eachitem)
              {
                  $carrier_name = $eachitem->carrier_name;
                 
              }
                 
              (double)$total_for_service = 0; 
              $boxing_array = array();
              $boxingarraycount = 0;
              $boxingarrayweight = 1;

              $boxesorganized = array();
                                         
              $makesurenotzeroNum = 0;
              foreach($groupedweightarray as $id=>$current_grouped_weight_array)
              { 
                 
                  foreach($current_grouped_weight_array as $currid => $currweight)
                  {
                      $itemWeight = $currweight;
                      $current_id = $currid;
                  } 
                 
                   if($boxingarrayweight + $itemWeight >= $service_weight_max)
                   {   
                       
                       $numinarray = count($boxesorganized);
                       $boxesorganized[$numinarray + 1] = $boxing_array;
                       $boxing_array = array();
                       $boxingarraycount = 0;
                       $boxingarrayweight = 1;
                       
                   }
                       $boxing_array[$boxingarraycount] = $current_grouped_weight_array;
                       $boxingarrayweight = $boxingarrayweight + $itemWeight;
                       $boxingarraycount++;
                   $makesurenotzeroNum++;           
              }
              if($makesurenotzeroNum > 0)
              {
                    $boxesorganized[count($boxesorganized) + 1] = $boxing_array;        
              }
             
             
              foreach($aloneweightarray as $key => $current_id_weight_array)
              {
                 
                  $newtmparray = array();
                  $newtmparray[0] = $current_id_weight_array;
                  $boxesorganized[count($boxesorganized) + 1] = $newtmparray;   
              }
             
             
                          
                  if($carrier_name == 'UPS') 
                  {       
                        foreach($boxesorganized as $key => $currentbox)
                        {
                            $total_box_weight = 1;
                            foreach($currentbox as $itemarray)
                            {
                                foreach($itemarray as $id=>$weight)
                                {
                                    $total_box_weight = $total_box_weight + $weight;
                                }    
                            }
                            //now do ups webservice call for this box
                            $shipping = ups($zip_code, $carrier_service_id, $total_box_weight);                             
                            $total_for_service = $total_for_service + $shipping;
                        }  
                             
                  }
                  else //carrier is USPS
                  {      
                        foreach($boxesorganized as $key => $currentbox)
                        {
                            $total_box_weight = 1;
                            foreach($currentbox as $itemarray)
                            {
                                foreach($itemarray as $id=>$weight)
                                {
                                    $total_box_weight = $total_box_weight + $weight;
                                }    
                            }
                            //now do usps webservice call for this box
                            //usps only accepts integer values for package in pounds. So we need to calculate the remaining ounces.
                            
                            $box_weight_in_pounds = 0.0;
                            $box_weight_in_ounces = 0.0;
                            if($total_box_weight < 1)
                            {
                                $box_weight_in_pounds = 0;
                                $box_weight_in_ounces = ceil($total_box_weight * 16);
                            }
                            else
                            {
                                $box_weight_in_pounds = floor($total_box_weight);
                                $box_weight_in_ounces = ceil(($total_box_weight - $box_weight_in_pounds)*16);
                            }
                            
                          
                             $return = (USPSParcelRate ($zip_code, $carrier_service_id, $box_weight_in_pounds, $box_weight_in_ounces));  
                             $subtotal = (double)$return;
                             $total_for_service = $total_for_service + $subtotal;
                        }
                         
                  }
                   
              
              
              
              $services_total[$service_id] = $total_for_service;
              $_SESSION['services_total'] = $services_total;
              $boxesforservice = "boxesorganized_service"  . $service_id;
              $_SESSION[$boxesforservice] = $boxesorganized;
              
           
            }
        }      
    }         
       

     ?>
    
   
    <form id="orderinformation" name="orderinformation" action="orderinformation.php" method="POST">
    <select name="service" onchange="document.orderinformation.submit();"> 
    <option value="0">Choose a shipping option</option>
    <?php
    $count = 0;
    foreach($services_total as $key => $value)
    {     
        $cost = $value;
        $cost = (double)$cost;  
        if($cost > 0)
        {          
            $current_service_id = $key;
            $getrequest = new shipping();
            $getrequest->service_id = $current_service_id;
            $getresponse = $getrequest->getshippingservicebyserviceid(); 
            $xml = new SimpleXMLElement($getresponse);
          
            foreach($xml as $eachitem)
            {      
                $current_service = $eachitem->service;   
                $current_carrier_id = $eachitem->carrier_id;         
                $current_carrier_id = (int)$current_carrier_id;
               
            }
            $getrequest = new shipping();
            $getrequest->carrier_id = $current_carrier_id; 
           
            $getresponse = $getrequest->getshippingcarrierbycarrierid();
            $xml = new SimpleXMLElement($getresponse);
            foreach($xml->Item as $eachitem)
            {
                $carrier_name = $eachitem->carrier_name;
               
            }   
            $string = $carrier_name . ':' . $current_service . ': ' . number_format($value, 2, '.', ''); 
            
            echo '<option value="' . $current_service_id . '" onclick="document.orderinformation.submit();">' . $string . '</option>';
        } 
        $count++;
    }
    if($count == 0)
    {
        echo "<option value='novalue'>one of your items disqualified you from shipping</option>";
        
         //if neither shipping service works because one of the values was too heavy then the admin needs to know about this problem
         $stringbuilder = "There was an error with the order shipping estimation calculator.  One of your items is heavier than all of the available services. \n";
         $stringbuilder .= "Please either delete the item or change it's weight so that it fits the available shipping services. \n";
         $stringbuilder .= "Below you will find the item ID(s) that caused this problem. \n\n\n";
         foreach($itemweightarray as $key => $weight)
         {
            $id = $sw_gw_id_array[$key];
            $stringbuilder .= "ID:" . $id . ", ";
         }
         $stringbuilder = rtrim($stringbuilder, ", ");
        
        //mail the admin this info
        
                     $mailarray = file('./configurational/mailconfiguration.php');
            $mailserverstring = "";
            $portstring = "";
            $usernamestring = "";
            $passwordstring = "";
            foreach($mailarray as $key => $value)
            {
                if(strpos($value, "mailserver") !== false)
                {
                    $mailserverstring = $value;
                }
                if(strpos($value, "port") !== false)
                {
                   $portstring = $value; 
                }
                if(strpos($value, "username") !== false)
                {
                    $usernamestring = $value;
                }
                if(strpos($value, "password") !== false)
                {
                    $passwordstring = $value;
                }
            }
            $mailusernamearray = explode("=", $usernamestring);
            $username = trim($mailusernamearray[1]);
            $passwordarray = explode("=", $passwordstring);
            $password = trim($passwordarray[1]);
            $portarray = explode("=", $portstring);
            $port = trim($portarray[1]);
            $hostarray = explode("=", $mailserverstring);
            $host = trim($hostarray[1]); 
         
            

         
          $from = $username;
          $to = $username;
          $body = $stringbuilder; 
          $subject = "Order Shipping Calculations Error."; 
          $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
          $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));

          $mail = $smtp->send($to, $headers, $body);
        
        
    }
    ?>
    </select>  
    </form>
    <br /> 
    <?php
    
    
   
    if(isset($_POST['service']))
    {
        //add the total sum price of the shipping service and the total sum prices of the items in the cart and assign these to session variables  
       // $subtotal = $_SESSION['total'];
         $service = $_POST['service'];    
         
         $temparray = $_SESSION['services_total'];
         $this_service_cost = $temparray[$service];
       
        $total = $this_service_cost + $itemprice;
        
        $_SESSION['service'] = $service;
        $shipping_object = new shipping();
        $shipping_object->service_id = $service;
        $shippingReturn = $shipping_object->getshippingservicebyserviceid();
        $shippingXml = new SimpleXMLElement($shippingReturn);
        foreach($shippingXml->Item as $eachItem)
        {
            $carrier_id = $eachItem->carrier_id;
            $shipping_object->carrier_id = $carrier_id;
            $carrierReturn = $shipping_object->getshippingcarrierbycarrierid();
            $carrierXml = new SimpleXMLElement($carrierReturn);
            foreach($carrierXml->Item as $carrierItem)
            {
                $carrier_name = (string)$carrierItem->carrier_name;
            }
        }
        echo 'Shipping Service:' . $carrier_name . ", " . $current_service;
        echo '<br />Shipping Total:' .  number_format($this_service_cost, 2, '.', '');
        echo '<br />Total After Shipping:' . number_format($total, 2, '.', '');
        $getrequest = new shipping();
        $getrequest->service_id = $service;
        $getresponse = $getrequest->getshippingservicebyserviceid();
        $xml = new SimpleXMLElement($getresponse);
        foreach($xml->Item as $eachitem)
        {
            $service_name = $eachitem->service; 
            $service_name = (string)$service_name;
          
        }
        $boxesorganized_service = "boxesorganized_service" . $service;
        $boxesorganized = $_SESSION[$boxesorganized_service];
        
        $_SESSION['boxesorganized'] = $boxesorganized;
        $_SESSION['shipping_identifier'] = $cartidentifier;
        $_SESSION['items_total'] = $itemprice;
        $_SESSION['service_name'] = $service_name;
        $_SESSION['shipping_total'] = $this_service_cost;
        $_SESSION['total_after_shipping'] = $total; 
        $_SESSION['service_id'] = $service;  
        $_SESSION['carrier_name'] = $carrier_name;
    
         
         $contents = array();
         $contents = file('./configurational/paymentconfiguration.php');
         
         $paypal = false;
         $creditcard = false;
         foreach($contents as $key => $value)
         {
             if(strpos($value, "paypal") !== false)
             {
                 $paypal = true;
             }
             if(strpos($value, "creditcard") !== false)
             {
                 $creditcard = true; 
             }
         }
           
         if($paypal == true && $creditcard == true)
         {
             echo '<b><h4>Choose Payment Method</h4><br />  </b>';
         }
         else
         { 
            echo '<b><h4>Available Payment Method</h4><br />  </b>';
         }
  
         if($paypal == true)
         {
               echo '<a href="./paypal.php"><img src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" BORDER=0/></a>';        
         }  
         if($paypal == true && $creditcard == true)
         {
             echo '<b><img src="./images/or.jpg" BORDER=0/></b>';
         }
         if($creditcard == true)
         {
               echo '<a href="./payment.php"><img src="./images/creditcard.jpg" BORDER=0/></a>';     
         }
     } 
       
    
    
    
    
    }       
}

?>
</div>
</body>

</html>
